package com.cyl.h5.controller;

import com.cyl.manager.act.domain.entity.FhMyai;
import com.cyl.manager.act.service.FhMyaiService;
import com.cyl.manager.ums.domain.entity.UserInfo;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ApiResponse;
import com.ruoyi.framework.config.LocalDataUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import okhttp3.*;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Scanner;

/**
 * @author sangsijing
 * @since 2025/6/5 10:24
 */
@Api(tags = "ai模型")
@RestController
@RequestMapping("/app/ai")
public class AiModelController extends BaseController {

    @Autowired
    private FhMyaiService fhmyai;

    // ✅ 定义在这里
    private static String cachedToken = null;
    private static long expireTime = 0;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String TOKEN_KEY = "baidu_ai_access_token";
    private static final OkHttpClient client = new OkHttpClient();
    private static final MediaType JSON_MEDIA_TYPE = MediaType.get("application/json; charset=utf-8");

    public static String getAccessToken() throws IOException {
        if (cachedToken != null && System.currentTimeMillis() < expireTime) {
            return cachedToken; // 使用缓存
        }
        //格式为https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=API Key&client_secret=Secret Key
        String apiKey = "A1IsbseqkKdFUNZB3Gv9XBr6";
        String secretKey = "wbGxUjPhrnUndXtIp5qWNYFrID0PFn7R";

        //注意这里更换为自己的API Key和Secret Key'
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+apiKey+"&client_secret="+secretKey;

        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(null, new byte[0]))
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("获取 access_token 失败，HTTP 状态码：" + response.code());
            }
            String responseBody = response.body().string();
            JsonObject jsonObject = new Gson().fromJson(responseBody, JsonObject.class);
            String accessToken  =jsonObject.get("access_token").getAsString();
            cachedToken = accessToken;
            int expiresIn = jsonObject.get("expires_in").getAsInt();
            expireTime = System.currentTimeMillis() + expiresIn * 1000L;
            return accessToken;
        }
    }


    @ApiOperation("千帆模型")
    @GetMapping("/model")
    public ApiResponse<String> model(@RequestParam String question) {
        try {
            String accessToken = getAccessToken();

            // 构建请求 URL
            String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=" + accessToken;
            //String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-pro-128k?access_token=" + accessToken;

            // 构建请求体
            JsonObject payload = new JsonObject();
            JsonArray messages = new JsonArray();
            JsonObject message = new JsonObject();
            message.addProperty("role", "user");
            message.addProperty("content", question);
            messages.add(message);
            payload.add("messages", messages);
            payload.addProperty("stream", false);
            payload.addProperty("temperature", 0.9);
            payload.addProperty("top_p", 0.7);
            payload.addProperty("penalty_score", 1);
            payload.addProperty("system", "钓鱼大师");
            payload.addProperty("max_output_tokens", 4096);
            payload.addProperty("frequency_penalty", 0.1);
            payload.addProperty("presence_penalty", 0.0);

            RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, payload.toString());

            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    return ApiResponse.error(500, "调用AI服务失败，状态码：" + response.code());
                }

                String responseBody = response.body().string();
                JsonObject responseJson = new Gson().fromJson(responseBody, JsonObject.class);

                if (responseJson.has("error_code")) {
                    int errorCode = responseJson.get("error_code").getAsInt();
                    String errorMsg = responseJson.get("error_msg").getAsString();
                    return ApiResponse.error(errorCode, errorMsg);
                }

                if (!responseJson.has("result")) {
                    return ApiResponse.error(400, "没有返回结果或结果格式不正确");
                }

                String answer = responseJson.get("result").getAsString();

                // 获取用户ID并保存问答记录
                UserInfo member = (UserInfo) LocalDataUtil.getVar(Constants.MEMBER_INFO);
                Long userId = member != null ? member.getId() : null;

                if (userId != null) {
                    FhMyai fhMyai = new FhMyai();
                    fhMyai.setKyword(question);
                    fhMyai.setContent(answer);
                    fhMyai.setUserId(userId);
                    fhmyai.insert(fhMyai);
                }

                return ApiResponse.success(answer);

            }
        } catch (Exception e) {
            return ApiResponse.error(500, "内部服务器错误：" + e.getMessage());
        }
    }


    @ApiOperation("图片识别推荐装备")
    @PostMapping("/recommendEquip")
    public String recommendEquip(@RequestParam("image") MultipartFile image) throws IOException {
        String accessToken = getAccessToken();

        // 百度云图像识别 API 地址
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=" + accessToken;

        // 将图片转换为字节数组
        byte[] imgData = image.getBytes();
        String imgStr = Base64.getEncoder().encodeToString(imgData);

        // 构建请求参数
        HashMap<String, Object> params = new HashMap<>();
        params.put("image", imgStr);

        // 发送 POST 请求
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, new Gson().toJson(params));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();
            JsonObject responseJson = new Gson().fromJson(responseBody, JsonObject.class);

            if (responseJson.has("result")) {
                JsonArray resultArray = responseJson.getAsJsonArray("result");
                // 处理结果，找到最相关的装备
                String recommendedEquip = processResult(resultArray);
                return recommendedEquip;
            } else {
                return "没有返回结果或结果格式不正确。";
            }
        }
    }

    private String processResult(JsonArray resultArray) {
        // 根据 resultArray 找到最相关的装备
        // 这里只是一个示例，实际需要根据具体业务逻辑来实现
        if (resultArray.size() > 0) {
            JsonObject firstResult = resultArray.get(0).getAsJsonObject();
            return firstResult.get("keyword").getAsString();
        }
        return "未找到相关装备";
    }

}
